/*
 * Created by IntelliJ IDEA.
 * User: amrk
 * Date: 24/04/2004
 * Time: 23:28:40
 */
package com.talios.jira.browser;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import com.talios.jira.JiraException;
import com.talios.jira.browser.signals.JiraServerDetails;
import com.talios.jira.idea.JiraConfiguration;
import com.talios.jira.idea.JiraConfigurationComponent;
import com.talios.jira.rpc.JiraRpcClient;
import com.talios.jira.settings.projects.ProjectComboBoxModel;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
import java.util.List;

/**
 * @jira INTPLUG-118 Blank dropdown lists in Create Issue Dialog
 */
public class IssueCreation {
    private static final Logger LOGGER = Logger.getInstance("Jira Browser");

    private JPanel mainPanel;
    private JComboBox servers;
    private JComboBox projects;
    private JPanel issueTypes;
    private JTextField title;
    private JTextArea environment;
    private JTextArea description;
    private JButton create;
    private JButton cancel;

    private static IssueCreation issueCreation;
    private String issueKey;

    private Project project;
    private JDialog dialog;
    private JComboBox fixFor;
    private JiraListComboBoxModel unleasedVersionsComboBoxModel;
    private ProjectComboBoxModel projectsComboBoxModel;
    private JiraRpcClient rpcClient;
    private List serverList;
    private JComboBox issueType;
    private JiraListComboBoxModel issueTypesComboBoxModel;
    private JiraServerDetails serverDetails;
    private JComboBox priority;
    private JComboBox affectedVersion;
    private JiraListComboBoxModel allVersionsComboBoxModel;
    private JiraListComboBoxModel prioritiesComboBoxModel;

    public JTextField getTitle() {
        return title;
    }

    public JTextArea getEnvironment() {
        return environment;
    }

    public IssueCreation(Project project) {
        this.project = project;

        dialog = new JDialog();
        dialog.setTitle("Create Issue");
        dialog.setModal(true);
        dialog.getContentPane().add(mainPanel);
        dialog.setBounds(400, 400, 500, 400);

        cancel.setIcon(IconLoader.getIcon("/actions/cancel.png"));
        create.setIcon(IconLoader.getIcon("/general/add.png"));

        JiraConfigurationComponent component = project.getComponent(JiraConfigurationComponent.class);
        JiraConfiguration config = component.getConfiguration();

        serverList = config.getServerList();
        servers.setModel(new ServerComboBoxModel(serverList));
        if (servers.getModel().getSize() > 0) {
            servers.setSelectedIndex(0);
        }

        updateProjectList(serverList);

        servers.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                create.setSelected(true);
                updateProjectList(serverList);
            }
        });

        projects.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                create.setSelected(true);
                updateProjectDetails();
            }
        });

        create.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                issueKey = createTheIssue();
            }
        });

        cancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dialog.setVisible(false);
            }
        });

    }

    private void updateProjectList(List serverList) {
        int index = servers.getSelectedIndex();

        if (index == -1) return;

        serverDetails = (JiraServerDetails) serverList.get(index);

        projectsComboBoxModel = new ProjectComboBoxModel(serverDetails.getProjectList());

        projects.setModel(projectsComboBoxModel);
        if (projects.getModel().getSize() > 0) {
            projects.setSelectedIndex(0);
        }

        prioritiesComboBoxModel = serverDetails.getIssuePrioritiesModel();
        priority.setModel(prioritiesComboBoxModel);
        if (priority.getModel().getSize() > 0) {
            priority.setSelectedIndex(0);
        }

        issueTypesComboBoxModel = serverDetails.getIssueTypesModel();
        issueType.setModel(issueTypesComboBoxModel);
        if (issueType.getModel().getSize() > 0) {
            issueType.setSelectedIndex(0);
        }

        updateProjectDetails();
        create.setEnabled(true);


    }

    private void updateProjectDetails() {
        JiraProjectDetails selectedItem = projectsComboBoxModel.getSelectedProject();
        if (selectedItem != null) {
            allVersionsComboBoxModel = selectedItem.getAllVersionsModel();
            allVersionsComboBoxModel.reverseItems();
            affectedVersion.setModel(allVersionsComboBoxModel);
            if (affectedVersion.getModel().getSize() > 0) {
                affectedVersion.setSelectedIndex(0);
            }

            unleasedVersionsComboBoxModel = selectedItem.getUnreleasedVersionsModel();
            unleasedVersionsComboBoxModel.reverseItems();
            fixFor.setModel(unleasedVersionsComboBoxModel);
            if (fixFor.getModel().getSize() > 0) {
                fixFor.setSelectedIndex(0);                                   
            }
        }
    }

    public String createIssue() {
        description.requestFocus();
        dialog.setVisible(true);
        return issueKey;
    }


    /**
     * Create an issue against a JIRA Project
     *
     * @return
     * @jira INTPLUG-118 Blank dropdown lists in Create Issue Dialog
     */
    private String createTheIssue() {

        try {
            JiraRpcClient rpc = new JiraRpcClient(serverDetails);
            Hashtable newIssue = rpc.createIssue(projectsComboBoxModel.getSelectedProject().getProjectKey(),
                    title.getText(), environment.getText(), description.getText(),
                    issueTypesComboBoxModel.getIdOfSelectedItem(),
                    prioritiesComboBoxModel.getIdOfSelectedItem(),
                    allVersionsComboBoxModel.getIdOfSelectedItem(),
                    unleasedVersionsComboBoxModel.getIdOfSelectedItem());

            dialog.setVisible(false);

            return (String) newIssue.get("key");
        } catch (JiraException e) {
            LOGGER.error("Unable to create new issue.");
        }
        return "";
    }

}